package com.hujie.sqlqueryes.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL预处理器实现类
 */
@Service
public class SqlPreprocessorImpl {
    
    private static final Logger logger = LoggerFactory.getLogger(SqlPreprocessorImpl.class);
    
    /**
     * 预处理SQL语句，为包含特殊字符的表名自动添加方括号
     * @param sql 原始SQL语句
     * @return 处理后的SQL语句
     */
    public String preprocessSql(String sql) {
        logger.debug("开始预处理SQL: {}", sql);
        
        // 匹配FROM子句后的表名（简单的正则表达式）
        Pattern fromPattern = Pattern.compile("(?i)(FROM\\s+)([\\w\\-]+)");
        Matcher fromMatcher = fromPattern.matcher(sql);
        StringBuffer sb = new StringBuffer();
        
        while (fromMatcher.find()) {
            String tableName = fromMatcher.group(2);
            // 如果表名包含连字符等特殊字符，则用方括号包围
            if (tableName.contains("-")) {
                fromMatcher.appendReplacement(sb, fromMatcher.group(1) + "[" + tableName + "]");
                logger.debug("为FROM子句中的表名添加方括号: {}", tableName);
            } else {
                fromMatcher.appendReplacement(sb, fromMatcher.group(0));
            }
        }
        fromMatcher.appendTail(sb);
        
        // 匹配INSERT INTO子句后的表名
        Pattern insertPattern = Pattern.compile("(?i)(INSERT\\s+INTO\\s+)([\\w\\-]+)");
        Matcher insertMatcher = insertPattern.matcher(sb.toString());
        StringBuffer sb2 = new StringBuffer();
        
        while (insertMatcher.find()) {
            String tableName = insertMatcher.group(2);
            // 如果表名包含连字符等特殊字符，则用方括号包围
            if (tableName.contains("-")) {
                insertMatcher.appendReplacement(sb2, insertMatcher.group(1) + "[" + tableName + "]");
                logger.debug("为INSERT INTO子句中的表名添加方括号: {}", tableName);
            } else {
                insertMatcher.appendReplacement(sb2, insertMatcher.group(0));
            }
        }
        insertMatcher.appendTail(sb2);
        
        // 匹配UPDATE子句后的表名
        Pattern updatePattern = Pattern.compile("(?i)(UPDATE\\s+)([\\w\\-]+)");
        Matcher updateMatcher = updatePattern.matcher(sb2.toString());
        StringBuffer sb3 = new StringBuffer();
        
        while (updateMatcher.find()) {
            String tableName = updateMatcher.group(2);
            // 如果表名包含连字符等特殊字符，则用方括号包围
            if (tableName.contains("-")) {
                updateMatcher.appendReplacement(sb3, updateMatcher.group(1) + "[" + tableName + "]");
                logger.debug("为UPDATE子句中的表名添加方括号: {}", tableName);
            } else {
                updateMatcher.appendReplacement(sb3, updateMatcher.group(0));
            }
        }
        updateMatcher.appendTail(sb3);
        
        // 匹配DELETE FROM子句后的表名
        Pattern deletePattern = Pattern.compile("(?i)(DELETE\\s+FROM\\s+)([\\w\\-]+)");
        Matcher deleteMatcher = deletePattern.matcher(sb3.toString());
        StringBuffer sb4 = new StringBuffer();
        
        while (deleteMatcher.find()) {
            String tableName = deleteMatcher.group(2);
            // 如果表名包含连字符等特殊字符，则用方括号包围
            if (tableName.contains("-")) {
                deleteMatcher.appendReplacement(sb4, deleteMatcher.group(1) + "[" + tableName + "]");
                logger.debug("为DELETE FROM子句中的表名添加方括号: {}", tableName);
            } else {
                deleteMatcher.appendReplacement(sb4, deleteMatcher.group(0));
            }
        }
        deleteMatcher.appendTail(sb4);
        
        String processedSql = sb4.toString();
        logger.debug("预处理完成的SQL: {}", processedSql);
        return processedSql;
    }
}